import time
import threading
from collections import deque

from camera.h264_camera import H264Camera
from tools.log import logger
h264_lock = threading.Lock()
h264_save_buffer = deque(maxlen=10)
activate_ts = time.time()


def work(global_conf,camera_conf):
    h264_camera = H264Camera(camera_conf["h264_camera"])
    check_ttk= 300/1000 # 300ms检查一次视频导出请求
    last_ts = time.time()
    output_ttk = camera_conf["h264_camera"]["front"]+camera_conf["h264_camera"]["back"]
    while True:
        try: 
            for packet in h264_camera.container.demux(h264_camera.video_stream):
                h264_camera.add_pkts(packet)    
                if(time.time()-last_ts)>check_ttk:
                    with h264_lock:
                        if len(h264_save_buffer)>0:
                            if h264_save_buffer[0][0]-activate_ts < h264_camera.pts_sec-camera_conf["h264_camera"]["back"]:
                                ts,meta = h264_save_buffer.pop()
                                pending_file = global_conf["environment"]+global_conf["share"]["pending"]["file"]
                                pending_lock = global_conf["environment"]+global_conf["share"]["pending"]["lock"]                                                
                                h264_camera.export_mp4(output_ttk,meta,pending_file,pending_lock)
                    last_ts = time.time()
        except Exception as e:
            h264_camera.connect_with_retry()        
            logger.error(e)